<template>
  <div class="schedule-calendar">

    <div class="calendar-container">
      <FullCalendarWrapper
        ref="calendarRef"
        :schedules="schedules"
        @date-click="handleDateClick"
        @event-click="handleEventClick"
        @date-select="handleDateSelect"
      />
    </div>

    <div class="calendar-legend">
      <div class="legend-item">
        <div class="legend-color priority-urgent"></div>
        <span>紧急</span>
      </div>
      <div class="legend-item">
        <div class="legend-color priority-high"></div>
        <span>高</span>
      </div>
      <div class="legend-item">
        <div class="legend-color priority-medium"></div>
        <span>中</span>
      </div>
      <div class="legend-item">
        <div class="legend-color priority-low"></div>
        <span>低</span>
      </div>
    </div>

    <!-- 添加日程模态框 -->
    <AddScheduleModal
      v-model:visible="addModalVisible"
      :default-date="selectedDate"
      :default-start-time="selectedStartTime"
      :default-end-time="selectedEndTime"
      @success="handleAddSuccess"
    />

    <!-- 编辑日程模态框 -->
    <EditScheduleModal
      v-model:visible="editModalVisible"
      :schedule-id="editingScheduleId"
      @success="handleEditSuccess"
    />

    <!-- 日程详情模态框 -->
    <ScheduleDetailModal
      v-model:visible="detailModalVisible"
      :schedule-id="viewingScheduleId"
      @edit="handleEditFromDetail"
      @delete="handleDeleteFromDetail"
      @refresh="handleRefreshFromDetail"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import type { ScheduleResponse } from '@/types/schedule';
import { useScheduleStore } from '@/stores/schedule';
import FullCalendarWrapper from './FullCalendarWrapper.vue';
import AddScheduleModal from './AddScheduleModal.vue';
import EditScheduleModal from './EditScheduleModal.vue';
import ScheduleDetailModal from './ScheduleDetailModal.vue';

interface Props {
  schedules?: ScheduleResponse[];
}

interface Emits {
  (e: 'date-select', date: string): void;
  (e: 'view-schedule', id: number): void;
}

const props = withDefaults(defineProps<Props>(), {
  schedules: () => []
});

const emit = defineEmits<Emits>();

const scheduleStore = useScheduleStore();
const calendarRef = ref();

// 视图状态
const currentView = ref('dayGridMonth');

// 模态框状态
const addModalVisible = ref(false);
const editModalVisible = ref(false);
const detailModalVisible = ref(false);
const selectedDate = ref<string | null>(null);
const selectedStartTime = ref<string | null>(null);
const selectedEndTime = ref<string | null>(null);
const editingScheduleId = ref<number | null>(null);
const viewingScheduleId = ref<number | null>(null);

// 格式化日期时间
const formatDateTime = (date: Date) => {
  return date.toISOString().slice(0, 19).replace('T', ' ');
};

// 视图控制方法
const previousPeriod = () => {
  calendarRef.value?.prev();
};

const nextPeriod = () => {
  calendarRef.value?.next();
};

const goToToday = () => {
  calendarRef.value?.today();
};

// 监听视图变化
watch(currentView, (newView) => {
  calendarRef.value?.changeView(newView);
});

// 处理日期点击
const handleDateClick = (date: Date) => {
  selectedDate.value = date.toISOString().split('T')[0];
  selectedStartTime.value = formatDateTime(date);
  
  // 设置默认结束时间为1小时后
  const endDate = new Date(date.getTime() + 60 * 60 * 1000);
  selectedEndTime.value = formatDateTime(endDate);
  
  addModalVisible.value = true;
  emit('date-select', selectedDate.value);
};

// 处理日期范围选择
const handleDateSelect = (start: Date, end: Date) => {
  selectedDate.value = start.toISOString().split('T')[0];
  selectedStartTime.value = formatDateTime(start);
  selectedEndTime.value = formatDateTime(end);
  
  addModalVisible.value = true;
};

// 处理事件点击
const handleEventClick = (schedule: ScheduleResponse) => {
  viewingScheduleId.value = schedule.id;
  detailModalVisible.value = true;
  emit('view-schedule', schedule.id);
};


// 编辑日程
const editSchedule = (id: number) => {
  editingScheduleId.value = id;
  editModalVisible.value = true;
};

// 处理模态框事件
const handleAddSuccess = async () => {
  await scheduleStore.fetchSchedules();
};

const handleEditSuccess = async () => {
  await scheduleStore.fetchSchedules();
};

const handleEditFromDetail = (id: number) => {
  detailModalVisible.value = false;
  editSchedule(id);
};

const handleDeleteFromDetail = async () => {
  await scheduleStore.fetchSchedules();
};

const handleRefreshFromDetail = async () => {
  await scheduleStore.fetchSchedules();
};

// 监听日程数据变化
watch(() => props.schedules, () => {
  // 日程数据更新时会自动重新渲染
}, { deep: true });


// 暴露方法供父组件调用
defineExpose({
  previousPeriod,
  nextPeriod,
  goToToday,
  changeView: (view: string) => {
    currentView.value = view;
  }
});
</script>

<style lang="scss" scoped>
.schedule-calendar {
  height: 100%;
  display: flex;
  flex-direction: column;
}


.calendar-container {
  flex: 1;
  overflow: hidden;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  border: 1px solid var(--el-border-color-light);
}

.calendar-legend {
  display: flex;
  gap: 20px;
  margin-top: 16px;
  padding: 12px;
  background: var(--el-bg-color);
  border-radius: var(--el-border-radius-base);
  border: 1px solid var(--el-border-color-light);
  
  .legend-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    color: var(--el-text-color-regular);
  }
  
  .legend-color {
    width: 16px;
    height: 16px;
    border-radius: var(--el-border-radius-small);
    
    &.priority-urgent {
      background: var(--el-color-danger);
    }
    
    &.priority-high {
      background: var(--el-color-warning);
    }
    
    &.priority-medium {
      background: var(--el-color-primary);
    }
    
    &.priority-low {
      background: var(--el-color-info);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .calendar-legend {
    flex-wrap: wrap;
    gap: 12px;
    
    .legend-item {
      font-size: 11px;
    }
    
    .legend-color {
      width: 12px;
      height: 12px;
    }
  }
}
</style>